package org.dreamfly.netshop.manage;

import java.util.ArrayList;
import java.util.List;

import org.dreamfly.netshop.dao.MemberDao;
import org.dreamfly.netshop.entity.Member;
import org.dreamfly.netshop.service.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.orm.PropertyFilter.MatchType;
import org.springside.modules.orm.hibernate.EntityManager;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;

/**
 * 用户管理类. 实现领域对象用户的所有业务管理函数. 演示派生DAO层子类的模式,由注入的UserDao封装数据库访问. 通过范型声明继承EntityManager,默认拥有CRUD管理方法. 使用Spring
 * annotation定义事务管理.
 * 
 * @author calvin
 */
// Spring Service Bean的标识.
@Service
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class MemberManager extends EntityManager<Member, Long> {
    @Autowired
    private MemberDao memberDao;

    /**
     * 实现回调函数,为EntityManager基类的CRUD操作提供DAO.
     */
    @Override
    protected MemberDao getEntityDao() {
        return memberDao;
    }

    /**
     * 重载delte函数,演示异常处理及用户行为日志.
     */
    @Override
    public void delete(Long id) {
        if (id == 1) {
            logger.warn("操作员{}尝试删除超级管理员用户", SpringSecurityUtils.getCurrentUserName());
            throw new ServiceException("不能删除超级管理员用户");
        }

        memberDao.delete(id);
    }

    public Member CheckUserAndPwd(Member member) {
        List<PropertyFilter> list = new ArrayList<PropertyFilter>();
        list.add(new PropertyFilter("name", member.getName(), MatchType.EQUAL));
        list.add(new PropertyFilter("password", member.getPassword(), MatchType.EQUAL));
        List<Member> mList = memberDao.findByFilters(list);
        return mList.size() != 1 ? null : mList.get(0);
    }

    public void deleteAllShopCart(Long id) {
        Member member = memberDao.find("from Member as o where o.id=?", id).get(0);
        member.setShopCarts(null);
        save(member);
    }

    public void modifyPassword(Member member) {
        memberDao.save(member);
    }

    public void modifyQAA(Member member) {
        Member m = get(member.getId());
        m.setPassword(member.getPassword());
        m.setQuestions(member.getQuestions());
        m.setAnswers(member.getAnswers());
        m.setAddress(member.getAddress());
        memberDao.save(m);
    }

    public void modifyInfo(Member member) {
        Member m = get(member.getId());
        m.setPassword(member.getPassword());
        m.setQuestions(member.getQuestions());
        m.setAnswers(member.getAnswers());
        m.setAddress(member.getAddress());
        memberDao.save(m);
    }
}
